package org.huangrui.design.pattern.singleton;

import java.util.concurrent.*;

/*
 * 懒汉式:
 *  延迟创建这个实例对象
 * (1)构造器私有化
 * (2)用一个静态变量保存这个唯一的实例
 * (3)提供一个静态方法，获取这个实例对象
 * @author hr
 * @create 2025-09-09 15:11
 */
public class Singleton4 {
	private static Singleton4 instance;
	private Singleton4(){
		
	}
	public static Singleton4 getInstance(){
		if(instance == null){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			instance = new Singleton4();
		}
		return instance;
	}

	public static void main(String[] args) throws ExecutionException, InterruptedException {
		/*Singleton4 s1 = Singleton4.getInstance();
		Singleton4 s2 = Singleton4.getInstance();
		System.out.println(s1);
		System.out.println(s2);
		System.out.println(s1 == s2);*/

		Callable<Singleton4> c = new Callable<Singleton4>() {
			@Override
			public Singleton4 call() throws Exception {
				return Singleton4.getInstance();
			}
		};
		ExecutorService es = Executors.newFixedThreadPool(2);
		Future<Singleton4> f1 = es.submit(c);
		Future<Singleton4> f2 = es.submit(c);
		Singleton4 s1 = f1.get();
		Singleton4 s2 = f2.get();
		System.out.println(s1);
		System.out.println(s2);
		System.out.println(s1 == s2);
		es.shutdown();
	}
}
